const express = require('express')
const router = express.Router()
const db = require('../sql/db')
const { md5 } = require('utility')
const jtk = require('jsonwebtoken')
const multer = require('multer')
const upload = multer({ dest: 'uploads/' })
// 注册
router.post('/api/reguser', function (req, res) {
    const { username, password } = req.body
    const pwd = md5(password)
    db(`INSERT into user set password='${pwd}',username='${username}'`, function (err, data) {
        if (err || data.affectedRows == 0) return res.send({ status: 1, message: '注册失败' })
        res.send({ status: 0, message: '注册成功' })
    })
})

//登录
router.post('/api/login', function (req, res) {
    const { username, password } = req.body
    const pwd = md5(password)
    db(`select * from user where password='${pwd}' and username='${username}'`, function (err, data) {
        console.log(err);
        if (err || data.length == 0) return res.send({ status: 1, message: '账号密码错误' })
        const token = jtk.sign({ id: data[0].id }, 'user', { expiresIn: '2h' })
        res.send({ status: 0, message: '登录成功', token: 'Bearer ' + token })
    })
})



// 获取用户的基本信息
router.get('/my/userinfo', function (req, res) {
    console.log(req.user);
    const { id } = req.user
    db(`select * from user where id=${id}`, function (err, data) {
        if (err) return res.send({ status: 1, message: '错误' })
        res.send({ status: 0, message: '登录成功', data })
    })
})

// 更新用户的基本信息
router.post('/my/userinfo', function (req, res) {
    const { nickname, email } = req.body
    const { id } = req.user
    db(`update user set nickname='${nickname}',email='${email}' where id='${id}'`, function (err, data) {
        console.log(err);
        if (err || data.changedRows == 0) return res.send({ status: 1, message: '修改错误' })
        res.send({ status: 0, message: '修改用户信息成功！' })
    })
})


// 重置密码
router.post('/my/updatepwd', function (req, res) {
    const { oldPwd, newPwd } = req.body
    const { id } = req.user
    const pwd = md5(oldPwd)
    db(`select * from user where password='${pwd}' and id='${id}'`, function (err, data) {
        if (err || data.length == 0) return res.send({ status: 1, message: '原密码密码错误' })
        const setpwd = md5(newPwd)
        db(`update user set password='${setpwd}' where id=${id}`, function (err, back) {
            if (err || back.changedRows == 0) return res.send({ status: 1, message: '密码修改错误' })
            res.send({ status: 0, message: '修改成功' })
        })
    })
})


// 更换头像
router.post('/my/update/avatar', upload.single('avatar'), function (req, res) {
    const { filename } = req.file
    const { id } = req.user
    db(`update user set user_pic='${filename}' where id='${id}'`, function (err, back) {
        if (err || back.changedRows == 0) return res.send({ status: 1, message: '修改失败' })
        res.send({ status: 0, message: '修改成功' })
    })
})


module.exports = router